// 对 axios 进行配置
import axios from 'axios';
import store from '@/store';
import {Loading} from 'element-ui';

let loadingInstance;
let service = axios.create({ // 创建 axios 实例
  baseURL: '/api', // 基础路径
  timeout: 5000 // 请求不能超过 5S
});

// 请求前拦截器
service.interceptors.request.use((request) => {
  loadingInstance = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  if (store.state.user.tokenHead && store.state.user.tokenValue) {
    // 请求头添加一个字段
    request.headers.common[store.state.user.tokenHead] = store.state.user.tokenValue;
    // config.headers.tokenHead = store.state.user.tokenValue;
  }
  return request;
});

// 请求后响应拦截器
service.interceptors.response.use((response) => {
  loadingInstance.close();
  if (response.status === 200) {
    return response.data;
  } else {
    console.error(response);
    return Promise.reject(new Error('faile'));
  }
}, (error) => {
  loadingInstance.close();
  console.error(error);
  return Promise.reject(new Error(JSON.stringify(error)));
});

// 暴露一个配置好了的 axios 实例
export default service;
